package com.fishingwithme.android.ui.screens.circle

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.SpotInCircleDto
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.components.MultiImageDisplay
import com.fishingwithme.android.ui.screens.anybitting.SwitchHandler
import com.fishingwithme.android.ui.screens.map.SideBar
import com.fishingwithme.android.ui.screens.map.SideBarItem
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.CircleDetailModel


@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CircleManageScreen(
    navController: NavController,
    id: String,
    viewModel: CircleDetailModel = hiltViewModel()
) {
    LaunchedEffect(id) {
        if (id.isNotEmpty()) {
            viewModel.getCircleDetail(id)
        }
    }

    val uiState by viewModel.uiState.collectAsState()
    var showAddSpots by remember { mutableStateOf(false) }
    var showAddMaintainer by remember { mutableStateOf(false) }

    val circleSpots = remember(viewModel, id) {
        viewModel.getCircleSpots()
    }.collectAsLazyPagingItems()
    val baseBarItems = remember {
        mutableListOf(
            SideBarItem(
                key = "add_spots",
                icon = R.mipmap.new_spot,
                handler = SwitchHandler("add_spots", R.mipmap.new_spot)
            ),
            SideBarItem(
                key = "show_maintainers",
                icon = R.mipmap.default_avatar,
                handler = SwitchHandler("show_maintainers", R.mipmap.default_avatar)
            ),
            SideBarItem(
                key = "update_circle",
                icon = R.mipmap.modify,
                handler = SwitchHandler("update_circle", R.mipmap.modify)
            )
        )
    }


    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        SideBar(
            barItems = baseBarItems,
            onItemClick = { handler ->
                var router: String? = null
                when (handler.key) {

                    "add_spots" -> {
                        showAddSpots = true
                    }

                    "show_maintainers" -> {
                        showAddMaintainer = true
                    }

                    "update_circle" -> {
                        router =
                            "${FishingNavigation.UPDATE_CIRCLE}?id=${uiState.detail?.id}"
                    }
                }

                if (router != null) {
                    navController.navigate(router)
                }
            }
        )

        when {
            uiState.isLoading -> {
                CircularProgressIndicator()
            }

            uiState.error != null -> {
                Text(
                    text = uiState.error!!,
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(AppDimensions.SPACING_16)
                )
            }

            uiState.detail != null -> {
                // Use LazyColumn as the single scrollable container instead of Column + verticalScroll
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(AppDimensions.SPACING_16)
                ) {
                    item {
                        val circle = uiState.detail

                        // 1. Display pictures at the top using MultiImageDisplay
                        circle?.pics?.let { pictures ->
                            MultiImageDisplay(
                                pictures = pictures,
                                modifier = Modifier.fillMaxWidth()
                            )
                        } ?: run {
                            // Show empty state if no pictures
                            MultiImageDisplay(
                                pictures = emptyList(),
                                modifier = Modifier.fillMaxWidth()
                            )
                        }

                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))

                        // 2. Title
                        Text(
                            text = circle?.title ?: stringResource(R.string.circle_title_unset),
                            style = MaterialTheme.typography.headlineMedium,
                            modifier = Modifier.fillMaxWidth()
                        )

                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))

                        // 3. City and isActive
                        Text(
                            text = "${circle?.city} ${
                                if (circle?.isActive == 1) stringResource(R.string.active) else stringResource(
                                    R.string.inactive
                                )
                            }",
                            style = MaterialTheme.typography.bodyLarge,
                            modifier = Modifier.fillMaxWidth()
                        )

                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_8))

                        // 4. spotCnt
                        Text(
                            text = "${stringResource(R.string.spot_count)}: ${circle?.spotCnt ?: 0}",
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier.fillMaxWidth()
                        )

                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_8))

                        // 5. maintainerCnt
                        Text(
                            text = "${stringResource(R.string.maintainer_count)}: ${circle?.maintainerCnt ?: 0}",
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier.fillMaxWidth()
                        )

                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_8))

                        // 6. area
                        Text(
                            text = "${stringResource(R.string.area)}: ${circle?.area ?: 0.0} km²",
                            style = MaterialTheme.typography.bodyMedium,
                            modifier = Modifier.fillMaxWidth()
                        )

                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))

                        // 描述卡片 - 独立显示
                        if (circle?.description?.isNotEmpty() ?: false) {
                            Card(
                                modifier = Modifier.fillMaxWidth(),
                                elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2)
                            ) {
                                Column(
                                    modifier = Modifier.padding(AppDimensions.SPACING_16)
                                ) {
                                    Text(
                                        text = stringResource(R.string.spot_description),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold
                                    )
                                    Spacer(modifier = Modifier.height(AppDimensions.SPACING_8))
                                    circle?.description?.let {
                                        Text(
                                            text = it,
                                            style = MaterialTheme.typography.bodyMedium
                                        )
                                    }
                                }
                            }

                            Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))
                        }

                        // Circle Spots Section
                        Text(
                            text = stringResource(R.string.circle_spots_title),
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier.fillMaxWidth()
                        )

                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_8))

                        // Display circle spots
                        // CircleSpotsList(circleSpots) - Removed as we've integrated this directly into the main LazyColumn
                    }

                    // Display circle spots using the same LazyColumn
                    items(
                        count = circleSpots.itemCount,
                        key = circleSpots.itemKey { it.id }) { index ->
                        circleSpots[index]?.let { spot ->
                            CircleSpotItem(spot)
                            // Add spacing between items
                            if (index < circleSpots.itemCount - 1) {
                                Spacer(modifier = Modifier.height(AppDimensions.SPACING_4))
                            }
                        }
                    }

                    // Handle empty state - show message when there are no items and not loading
                    if (circleSpots.itemCount == 0 && circleSpots.loadState.refresh is LoadState.NotLoading) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(AppDimensions.SPACING_16),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = stringResource(R.string.no_circle_spots),
                                    style = MaterialTheme.typography.bodyMedium
                                )
                            }
                        }
                    }

                    // Handle loading states
                    when {
                        circleSpots.loadState.refresh is LoadState.Loading -> {
                            item {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(AppDimensions.SPACING_16),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            }
                        }

                        circleSpots.loadState.append is LoadState.Loading -> {
                            item {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(AppDimensions.SPACING_16),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            }
                        }

                        circleSpots.loadState.refresh is LoadState.Error -> {
                            val error = (circleSpots.loadState.refresh as LoadState.Error).error
                            item {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(AppDimensions.SPACING_16),
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = stringResource(
                                            R.string.circle_spots_load_failed,
                                            error.message ?: "Unknown error"
                                        ),
                                        color = MaterialTheme.colorScheme.error,
                                        style = MaterialTheme.typography.bodyMedium
                                    )
                                    Spacer(modifier = Modifier.height(AppDimensions.SPACING_8))
                                    // Add retry button
                                    androidx.compose.material3.Button(
                                        onClick = { circleSpots.retry() }
                                    ) {
                                        Text(stringResource(R.string.circle_spots_retry))
                                    }
                                }
                            }
                        }
                    }
                }
            }

            else -> {
                Text(
                    text = stringResource(R.string.no_data_available),
                    style = MaterialTheme.typography.bodyLarge
                )
            }
        }
    }
}

@Composable
fun CircleSpotItem(spot: SpotInCircleDto) {
    Card(
        modifier = Modifier
            .fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppDimensions.SPACING_12)
        ) {
            Text(
                text = spot.name ?: stringResource(R.string.circle_spot_untitled),
                style = MaterialTheme.typography.titleMedium
            )

            Spacer(modifier = Modifier.height(AppDimensions.SPACING_4))

            Text(
                text = "${spot.city ?: stringResource(R.string.circle_spot_unknown_city)} ${
                    if (spot.isPrivate == 1) stringResource(R.string.circle_spot_private) else stringResource(
                        R.string.circle_spot_public
                    )
                } ${
                    if (spot.isFree == 1) stringResource(R.string.circle_spot_free) else stringResource(
                        R.string.circle_spot_paid
                    )
                }",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}